package com.ikkong.api;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.druid.util.StringUtils;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.toolbox.Record;
import com.ikkong.platform.model.Member;
import com.ikkong.platform.service.MemberService;
import com.ikkong.platform.service.SmsService;
import com.ikkong.platform.service.impl.MemberServiceImpl;
import com.ikkong.platform.service.impl.SmsServiceImpl;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.ext.interceptor.POST;
import com.ikkong.api.intercept.CommonInterceptor;
import com.ikkong.api.intercept.TokenInterceptor;
import com.ikkong.api.model.BaseResponse;
import com.ikkong.api.model.Code;
import com.ikkong.api.model.DatumResponse;
import com.ikkong.api.model.FileResponse;
import com.ikkong.api.model.LoginResponse;
import com.ikkong.api.util.SMSUtils;
import com.ikkong.api.TokenManager;

/**
 * 用户账号相关的接口*
 */
@Before({ CommonInterceptor.class, TokenInterceptor.class })
public class UserApiController extends BaseAPIController {
		private static SmsService snsService = new SmsServiceImpl();
		private static MemberService memberService = new MemberServiceImpl();
	

		/**
		 * 1. 检查是否被注册* 2. 发送短信验证码 
		 * param: 1:mphone 手机号,2:type 类型（1.注册;2.登录，3。更换手机号;4.车位认证）
		 */
		@Before(POST.class)
		@Clear(TokenInterceptor.class)
		public void sendCode() {
			try {
				String mphone = getPara("mphone");
				if (StringUtils.isEmpty(mphone)) {
					renderArgumentError("mphone参数未传入");
					return;
				}

				// 检查手机号码有效性
				if (!SMSUtils.isMobileNo(mphone)) {
					renderArgumentError("手机号不合法");
					return;
				}
				String smsCode = SMSUtils.randomSMSCode(4);
				boolean flag = true;
				// 发送短信验证码
				String errMsg = snsService.sendCode(mphone, smsCode);

				if (!errMsg.isEmpty()) {
					renderFailed(errMsg);
					return;
				}
				renderSuccess("短信发送成功" + smsCode);
			} catch (Exception e) {
				renderError(e.getMessage());
			}
		}
		
	 /**
		 * 发送短信方法 1.手机号 mphone，2.短信内容 content
		 * *//*
		@Before(POST.class)
		@Clear(TokenInterceptor.class)
		public void sendSMS() {
			try {
				// 手机号
				String mphone = getPara("mphone");
				if (mphone.isEmpty()) {
					renderJson(new BaseResponse(Code.FAIL, "手机号不能为空"));
					return;
				}
				// 检查手机号码有效性
				if (!SMSUtils.isMobileNo(mphone)) {
					renderArgumentError("手机号不合法");
					return;
				}
				// 内容
				String content = getPara("content");
				if (content.isEmpty()) {
					renderJson(new BaseResponse(Code.FAIL, "内容不能为空"));
					return;
				}
				boolean flag = SMSUtils.sendSMS(mphone, content);
				renderJson(new BaseResponse(flag ? Code.SUCCESS : Code.FAIL,
						flag ? "短信发送成功" : "短信发送失败"));

			} catch (Exception e) {
				renderJson(new BaseResponse(Code.ERROR, e.getMessage()));
			}
		}*/

		/**
		 * 注册/登录(如果没有账号没有注册，先进行注册) param: 1:mphone 手机号,2:code 验证码
		 */
		@Before(POST.class)
		@Clear(TokenInterceptor.class)
		public void postLogin() {
			try {

				String mphone = getPara("mphone");
				String code = getPara("code");
				// 获取手机验证码
				String smsCode = snsService.getSMSCode(mphone);
				if (StringUtils.isEmpty(code)) {
					renderArgumentError("验证码不能为空");
					return;
				}

				if (StringUtils.isEmpty(mphone)) {
					renderArgumentError("手机号不能为空");
					return;
				}
				// 检查手机号码有效性
				if (!SMSUtils.isMobileNo(mphone)) {
					renderArgumentError("手机号不合法");
					return;
				}

				if (StringUtils.isEmpty(smsCode)) {
					renderFailed("验证码未获取到，请重新发送验证码");
					return;
				}

				// 检查验证码是否有效, 如果业务不需要，则无需保存此段代码
				if (!code.equals(smsCode)) {
					renderFailed("验证码不正确");
					return;
				}

				// 检查账户是否已被注册
				Blade blade = Blade.create(Member.class);
				Member member = blade.findFirstBy("phone=#{mphone}", Record
						.create().set("mphone", mphone));
				LoginResponse response = new LoginResponse();
				if (member == null) {
				member = new Member();
					member.setPhone(mphone);
					member.setName(mphone);
					member.setUsername(mphone);
					member.setCreateime(new Date());
					int rid = blade.saveRtId(member);
					member.setId(rid);

				}
				Map<String, Object> userInfo = new HashMap<String, Object>();
				userInfo.put("phone", member.getPhone());
				userInfo.put("name", member.getName());
				userInfo.put("username", member.getUsername());
				userInfo.put("avatar", member.getAvatar());
				userInfo.put("bank_id", member.getBank_id());
				//userInfo.put("sex", member.getSex());
				//userInfo.put("credit", member.getCredit());
				//userInfo.put("wxid", member.getWXID());
				response.setInfo(userInfo);
				response.setMessage("登录成功");
				response.setToken(TokenManager.getMe().generateToken(member));
				renderJson(response);

			} catch (Exception e) {
				renderError(e.getMessage());
				
			}
		}
		/***
		 * 查询用户资料 token=0c4af5ea18bd4d3db7b442e6447e68155jhbw5
		 */
		@Before(POST.class)
		public void getUserInfo() {
			DatumResponse response = new DatumResponse();
			try {
				Member member = getUser();
				int userId = member.getId();
				// 检查账户是否已被注册
				Blade blade = Blade.create(Member.class);
				Member user = blade.findFirstBy("id=#{userId}", Record.create()
						.set("userId", userId));
				if (user == null) {
					renderFailed("用户未找到");
					return;
				} else {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("member_id", user.getId());
					map.put("phone", user.getPhone());
					map.put("name", user.getName());
					map.put("username", user.getUsername());
					map.put("avatar", user.getAvatar());
					map.put("bank_id", user.getBank_id());
					response.setDatum(map);
				}

				renderJson(response);
			} catch (Exception e) {
				renderError(e.getMessage());
			}
		}

		/**
		 * 修改用户资料 param:nickName或者email token=0c4af5ea18bd4d3db7b442e6447e68155jhbw5
		 */
		@Before(POST.class)
		public void updateUser() {
			BaseResponse response = new BaseResponse();
			try {
				boolean flag = false;
				Member user = getUser();
				String nickName = getPara("nickName", user.getName());
				String email = getPara("email", user.getEmail());

				if (!StringUtils.isEmpty(nickName)) {
					flag = true;
				} else if (!StringUtils.isEmpty(email)) {
					flag = true;
				}

				// 修改性别
				/*
				 * Integer sex = getParaToInt("sex", null); if (null != sex) { if
				 * (!User.checkSex(sex)) { renderArgumentError("sex is invalid");
				 * return; } user.set(SEX, sex); flag = true; }
				 */

				if (flag) {
					Blade blade = Blade.create(Member.class);
					boolean update = blade.updateBy(
							"name=#{name},email=#{email}",
							"id=#{user_id}",
							Record.create().set("name", nickName)
									.set("email", email)
									.set("user_id", user.getId()));
					// boolean update = blade.update(user);
					if (update) {
						// user.setName(nickName);
						// user.setEmail(email);

					}
					renderJson(response.setCode(update ? Code.SUCCESS : Code.FAIL)
							.setMessage(update ? "更新成功" : "更新失败"));
				} else {
					renderFailed("您没有要修改的信息");
				}
			} catch (Exception e) {
				renderError(e.getMessage());
			}
		}

		/**
		 * 修改头像接口 参数:1.token 签名 2:avatar 图片文件 头像路径
		 */
		@Before(POST.class)
		public void avatar() {
			FileResponse response = new FileResponse();
			try {

				String avatar = getPara("avatar");
				if (avatar.isEmpty()) {
					renderArgumentError("您没有上传头像");
					return;
				}
				Member member = getUser();
				Blade blade = Blade.create(Member.class);

				blade.updateBy("avatar=#{avatar}", "id=#{uid}", Record.create()
						.set("avatar", avatar).set("uid", member.getId()));
				response.setCode(Code.SUCCESS);
				response.setDatum(avatar);
				renderJson(response);
			} catch (Exception e) {
				renderError(e.getMessage());
			}
		}

		/**
		 * 更换手机号 param: 1:mphone 手机号,2:code 验证码
		 * token=0c4af5ea18bd4d3db7b442e6447e68155jhbw5 /api/account/updatePhone
		 */
		@Before(POST.class)
		public void updatePhone() {
			try {
				String code = getPara("code");
				String oldPhone = getPara("oldPhone");
				String newPhone = getPara("newPhone");

				String smsCode = snsService.getSMSCode(newPhone);
				if (oldPhone.isEmpty()) {
					renderArgumentError("没有填写原手机号");
									return;
				}
				// 检查手机号码有效性
				if (!SMSUtils.isMobileNo(oldPhone)) {
					renderFailed("原手机号不合法");
					return;
				}

				if (newPhone.isEmpty()) {
					renderArgumentError("没有填写新的手机号");
								return;
				}
				// 检查手机号码有效性
				if (!SMSUtils.isMobileNo(newPhone)) {
					renderFailed("新的手机号不合法");
					return;
				}

				if (StringUtils.isEmpty(smsCode)) {
					renderFailed("未获取到验证码，请重新发送验证码");
					return;
				}

				// 检查验证码是否有效, 如果业务不需要，则无需保存此段代码
				if (!code.equals(smsCode)) {
					renderJson(new BaseResponse(Code.CODE_ERROR, "验证码不正确"));
					return;
				}

				Member member = getUser();
				int user_id = member.getId();

				Blade blade = Blade.create(Member.class);

				Member user = blade.findById(user_id);
				if (!user.getPhone().equals(oldPhone)) {
					renderJson(new BaseResponse(Code.FAIL, "原手机号码不正确"));
					return;
				}

				int countNewPhone = blade.count("phone=#{phone}", Record.create()
						.set("phone", newPhone));
				if (countNewPhone > 0) {
					renderJson(new BaseResponse(Code.FAIL, "新的手机号码已经绑定过账号"));
					return;
				}
				boolean flag = blade.updateBy(
						"phone=#{phone}",
						"id=#{user_id}",
						Record.create().set("phone", newPhone)
								.set("user_id", user_id));
				if (flag == true) {
					renderJson(new BaseResponse(Code.SUCCESS));
				} else {
					renderJson(new BaseResponse(Code.FAIL, "更新失败"));
				}
				renderJson(new BaseResponse(Code.SUCCESS));
			} catch (Exception e) {
				renderJson(new BaseResponse(Code.ERROR, e.getMessage()));
			}
		}

}
